package com.jushu.storbox.util;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.callback.IUpdateStateChangeListener;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.view.dialog.ProgressDownloader;
import com.jushu.storbox.view.viewImpl.ITextView;
import com.huawei.sharedrive.sdk.android.modelV2.request.ClientInfoResponseV2;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class UpgradeUtils {

	private final static String LOG_TAG = "UpgradeUtils";
	private Context context;
	private String downloadUrl = "";
	private String strNewVersion = "";
	private long totalSize = 0l;
	private String packageName = "";
	private String cnexplain = "";
	private String enexplain = "";
	private IUpdateStateChangeListener mOnUpdateStateChangeListener;

	public UpgradeUtils(Context context) {
		// TODO Auto-generated constructor stub
		this.context = context;
	}

	
	public IUpdateStateChangeListener getOnUpdateStateChangeListener() {
		return mOnUpdateStateChangeListener;
	}

	public void setOnUpdateStateChangeListener(
			IUpdateStateChangeListener muOnUpdateStateChangeListener) {
		this.mOnUpdateStateChangeListener = muOnUpdateStateChangeListener;
	}

	public void upgradeCloudDrive(ClientInfoResponseV2 versionInfo, boolean makeTxt) {
		if(versionInfo == null){
//			if(makeTxt){
//				Toast.makeText(context, R.string.no_newer_version, Toast.LENGTH_SHORT).show();
//			}
//			return;
		}
		if(StringUtil.isBlank(versionInfo.getDownloadUrl()) || StringUtil.isBlank(versionInfo.getVersionInfo())){
//			if(makeTxt){
//				Toast.makeText(context, R.string.no_newer_version, Toast.LENGTH_SHORT).show();
//			}
//			return;
		}
		String versionStr = versionInfo.getVersionInfo();
		downloadUrl = versionInfo.getDownloadUrl();
		int versionNum = 0;
		try{
			if(StringUtil.isNotBlank(versionStr)){
				//versionStr = versionStr.replaceAll(" ", "");
				String[] pairs = versionStr.split("\n|\r\n|\r");
				for(String pair : pairs){
					String[] keyValue = pair.split("=");
					if("VersionNo".equals(keyValue[0])){
						versionNum = Integer.parseInt(keyValue[1]);
					}
					if("Version".equals(keyValue[0])){
						strNewVersion = keyValue[1];
					}
					if("TotalSize".equals(keyValue[0])){
						totalSize = Long.parseLong(keyValue[1]);
					}
					if("ChineseDesc".equals(keyValue[0])){
						cnexplain = keyValue[1];
					}
					if("EnglishDesc".equals(keyValue[0])){
						enexplain = keyValue[1];
					}
				}
			}
			packageName = "Onebox_V" + strNewVersion + ".apk";
		}catch(Exception e){
			LogUtil.e(LOG_TAG, "Upgrade,Resolve version info fail");
			if(makeTxt){
				Toast.makeText(context, R.string.no_newer_version, Toast.LENGTH_SHORT).show();
			}
			return;
		}
		if(versionNum > PublicTools.getVersionCode(context)){
			Dialog dialog = buildShowUpdateInfoDialog(context);
			// android:name="android.permission.SYSTEM_ALERT_WINDOW" />
			dialog.getWindow().setType(
					WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setCancelable(false);
			dialog.show();
			return;
//			if (!ShareDriveApplication.getInstance().updateDialogFlag) {
//				LogUtil.i(LOG_TAG, "show cloud drive upgrade dialog...");
//				dialog.show();
//				ShareDriveApplication.getInstance().updateDialogFlag = true;
//			}
		}else{
//			if(makeTxt){
//				Toast.makeText(context, R.string.no_newer_version, Toast.LENGTH_SHORT).show();
//			}
			return;
		}
	}

	private Dialog buildShowUpdateInfoDialog(Context context){
		final ClouddriveDialog dialog = new ClouddriveDialog(context,
				R.style.dialog_upload, R.layout.dialog_update_info);
		dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		View conventView = dialog.getConventView();
		Button dialog_cancal = (Button) conventView
				.findViewById(R.id.dialog_add_file_cancal_bt);

		Button dialog_OK = (Button) conventView
				.findViewById(R.id.dialog_add_file_ok_bt);

		ITextView tv = (ITextView) conventView
				.findViewById(R.id.dialog_prompt_tv);
		String clientUpdateInfo = (String) context.getText(R.string.new_version);
		
		if (PublicTools.isLocaleLanguageCN()) {
			if(cnexplain == null|| cnexplain.trim().equals("")){
				tv.setIText(clientUpdateInfo);
			}else{
				tv.setIText(cnexplain);
			}
		} else {
			if(enexplain == null|| enexplain.trim().equals("")){
				tv.setIText(clientUpdateInfo);
			}else{
				tv.setIText(enexplain);
			}
		}
		TextView title = (TextView) conventView.findViewById(R.id.tv_title);
//		builder.setTitle(context.getString(R.string.main_activity_update_title) + "v" + PublicTools.getVersionName(context) + "->v" + strNewVersion);
		title.setText(context.getString(R.string.main_activity_update_title));
		dialog_OK.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
//						ShareDriveApplication.getInstance().updateDialogFlag = false;
						dialog.dismiss();
						if (StringUtil.isNotBlank(downloadUrl)){
							downloadApkFile(packageName, downloadUrl, totalSize);
						}
					}
				});
		dialog_cancal.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ShareDriveApplication.getInstance().updateDialogFlag = false;
				dialog.dismiss();
			}
		});
		return dialog;
		
	}
	

	private void downloadApkFile(final String apkName, final String url,
			final long totalSize) {
		ProgressDownloader downloader = ProgressDownloader.getInstance(context, apkName, url, totalSize);
		SharedPreferences settings = context
				.getSharedPreferences(ClientConfig.settings,
						Context.MODE_APPEND);
		int status = settings.getInt(ClientConfig.UPGRADE_APK_DOWNLOAD_STATUS, -1);
		if(status == Constant.APK_NOW_IS_DOWNLOADING){
			downloader.showProgress();
		}else{
			if(mOnUpdateStateChangeListener != null){
				mOnUpdateStateChangeListener.onStartDownloadAPK();
			}
			downloader.download();
		}
		
	
	}

//	private Handler mHandler = new Handler() {
//		public void handleMessage(Message msg) {
//			switch (msg.what) {
//			case 8001:// update download dialog
//				String perProgress = (String) msg.obj;
//				updateDialog.updateMessage(context
//						.getString(R.string.main_activity_update_now_download)
//						+ perProgress + "%");
//				updateDialog.setProgress(Integer.valueOf(perProgress));
//				break;
//			case 8003:// cutoff network & install iDesk
//				LogUtil.i(LOG_TAG, "downloadFile logout.");
//				PublicTools.installApk(context.getApplicationContext(),
//						Environment.getExternalStorageDirectory() + "/"
//								+ "CloudDrive.apk");
//				break;
//			case 8888:// execute upgrade
//				SharedPreferences settings = context.getSharedPreferences(
//						ClientConfig.settings, Context.MODE_APPEND);
//				Editor editor = settings.edit();
//				if (checkAppUpdate()) {
//					//listening,need update
//					if(mOnUpdateStateChangeListener != null){
//						mOnUpdateStateChangeListener.onEndCheckIsNeedUpdate(true);
//					}
//					
//					//
//					editor.putBoolean(Constant.CLOUD_UPGRADE_STATE, true);
//					editor.commit();
//					
//					//
////					updateDialog = new CloudProgressDialog(context);
//					String clientUpdateInfo = context.getString(R.string.introducation_new_version);
////					Dialog dialog = buildUpdateDialog(context,
////							clientUpdateInfo, downloadUrl, totalSize);
//					Dialog dialog = buildShowUpdateInfoDialog(context);
//					// <uses-permission
//					// android:name="android.permission.SYSTEM_ALERT_WINDOW" />
//					dialog.getWindow().setType(
//							WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//
//					dialog.setCanceledOnTouchOutside(false);
//					dialog.setCancelable(false);
//					if (!ShareDriveApplication.getInstance().updateDialogFlag) {
//						LogUtil.i(LOG_TAG, "show cloud drive upgrade dialog...");
//						dialog.show();
//						ShareDriveApplication.getInstance().updateDialogFlag = true;
//					}
//				} else {
//					if(mOnUpdateStateChangeListener != null){
//						mOnUpdateStateChangeListener.onEndCheckIsNeedUpdate(false);
//					}
//					editor.putBoolean(Constant.CLOUD_UPGRADE_STATE, false);
//					editor.commit();
//				}
//				
//				break;
//				
//			case 8099://download success
//				SharedPreferences settings1 = context.getSharedPreferences(
//						ClientConfig.settings, Context.MODE_APPEND);
//				Editor editor1 = settings1.edit();
//				editor1.putInt(ClientConfig.UPGRADE_APK_DOWNLOAD_STATUS, Constant.APK_NOT_IN_DOWNLOADING);
//				editor1.commit();
//				break;
//				
//			case 8110://download fail
//				SharedPreferences settings2 = context.getSharedPreferences(
//						ClientConfig.settings, Context.MODE_APPEND);
//				Editor editor2 = settings2.edit();
//				editor2.putInt(ClientConfig.UPGRADE_APK_DOWNLOAD_STATUS, Constant.APK_DOWNLOAD_FAIL);
//				editor2.commit();
//				break;
//				
//				
//			
//			}
//			super.handleMessage(msg);
//		}
//	};
	
}
